import React, { useState, useEffect } from 'react';
import { View, Input, Text } from '@tarojs/components';
import './style.scss';

const inputNum = 6;

const Index = ({ onChange, type, text }) => {
  const [isFocus, setFocus] = useState(false);

  const [val, setVal] = useState({});
  const inputHandler = (key, e) => {
    let {
      detail: { value },
    } = e;
    let updateVal = {};
    for (let i = 0; i < inputNum; i++) {
      if (i < value.length) {
        updateVal[`code${i}`] = value[i];
      } else {
        updateVal[`code${i}`] = '';
      }
    }
    setVal({
      ...val,
      ...updateVal,
      [key]: value,
    });
  };

  const renderInput = (len) => {
    let result = [];
    for (let i = 0; i < len; i++) {
      result.push(
        <Input
          key={`code${i}`}
          className="password-input"
          type={type}
          disabled
          maxlength={1}
          value={val[`code${i}`] || ''}
          onClick={() => {
            setFocus(true);
          }}
        />,
      );
    }
    return result;
  };

  useEffect(() => {
    onChange && onChange(val.main);
  }, [val]);

  useEffect(() => {
    return () => {
      setVal({});
    };
  }, []);

  return (
    <View className="set-password-view">
      <Text className="text">{text}</Text>
      <Input
        focus={isFocus}
        className="main-input"
        type={type}
        maxlength={inputNum}
        onInput={(e) => {
          inputHandler('main', e);
        }}
        onBlur={() => {
          setFocus(false);
        }}
      />
      {renderInput(inputNum)}
    </View>
  );
};
export default Index;
